<?php

class MainController extends Controller {

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        $baseUrl = Yii::app()->request->baseUrl . '/';
        $region = $this->getRegion();
        $sql1 = 'SELECT pr.*, p.prod_title, p.prod_url, p.prod_count, p.prod_image, p.prod_id FROM mp_products p
                    LEFT JOIN mp__pr_prices pr ON pr.prod_id = p.prod_id AND pr.region_id=' . $region['id'] . '
                    WHERE p.prod_type = \'new\' ORDER BY p.prod_sort LIMIT 12';

        $sql2 = 'SELECT pr.*, p.prod_title, p.prod_url, p.prod_count, p.prod_image, p.prod_id FROM mp_products p
                    LEFT JOIN mp__pr_prices pr ON pr.prod_id = p.prod_id AND pr.region_id=' . $region['id'] . '
                    WHERE p.prod_type = \'popular\' ORDER BY p.prod_sort LIMIT 12';
        $new = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql1)->queryAll();
        $popular = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql2)->queryAll();
        $this->render('index', array('baseUrl' => $baseUrl, 'new' => $new, 'popular' => $popular));
    }

    public function actionProducts() {
        $baseUrl = Yii::app()->request->baseUrl . '/';
        $this->breadcrumbs = $this->getBreadcrumbs();
        $models = self::$pageData;
        if (isset($_GET['types'])) {
            $region = $this->getRegion();
            $sql = 'SELECT
                        pr.*, p.prod_title, p.prod_url, p.prod_count, p.prod_image, p.prod_id
                       FROM
                        mp_products P
                       LEFT JOIN mp__pr_prices pr ON pr.prod_id = p.prod_id AND pr.region_id = ' . $region['id'] . '
                       WHERE p.prod_id IN (SELECT prod_id FROM mp_prod2ch WHERE ch_id IN (' . str_replace('/', ',', $_GET['types']) . ')) ORDER BY p.prod_sort';
            $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        }
        $this->render('products', array('baseUrl' => $baseUrl, 'models' => $models));
    }

    public function actionProduct() {
        $baseUrl = Yii::app()->request->baseUrl . '/';
        $sql = 'SELECT * FROM mp_prices WHERE price_active=1';
        $prices = Yii::app()->db->createCommand($sql)->queryAll();
        $this->render('product', array('baseUrl' => $baseUrl, 'model' => self::$pageData, 'prices' => $prices));
    }

    public function actionOrder() {
        $this->breadcrumbs = array(
            'Оформление заказа' => '/',
        );
        $orderPrefixList = array('MS', 'SP', 'NN', 'EK', 'NK', 'KN');
        $region = $this->getRegion();
        $orderPrefix = isset($orderPrefixList[$region['id'] - 1]) ? $orderPrefixList[$region['id'] - 1] : 'MS';
        $orderPrefix .= rand(20, 90000);
        if (!isset($_COOKIE['basket']))
            $this->redirect('/');
        $products = json_decode($_COOKIE['basket'], true);
        $products = array_filter($products['rows']);

        $model = new OrderForm();
        $this->performAjaxValidation($model);
        if (isset($_POST['OrderForm'])) {
            $model->attributes = $_POST['OrderForm'];
            if ($model->validate()) {
                $u = Users::model()->find('user_email=:user_email', array(':user_email' => $_POST['OrderForm']['email']));
                if (!$u && Yii::app()->user->isGuest) {
                    $user = new Users();
                    $user->user_login = $_POST['OrderForm']['email'];
                    $user->user_email = $_POST['OrderForm']['email'];
                    $user->user_type = 'user';
                    $user->user_phone = $_POST['OrderForm']['phone'];
                    $user->user_password = md5('123');
                    $user->save(false);
                    $uID = $user->user_id;
                } else
                    $uID = $u->user_id;
                $connection = Yii::app()->db;
                $transaction = $connection->beginTransaction();
                try {
                    foreach ($products as $product) {
                        $data = array(
                            'log_type' => 1,
                            'log_time' => time(),
                            'log_description' => 'Заказ ЗЧ',
                            'log_prod_id' => $product['id'],
                            'log_wh_id' => $_POST['OrderForm']['warehouse'],
                            'log_prod_count' => $product['quantity'],
                            'log_price_id' => 0,
                            'log_price_sum' => $product['quantity'] * $product['price'],
                            'log_curr' => 0,
                            'log_price_rouble' => $product['price'],
                            'log_delivery_sum' => $product['price'],
                            'log_delivery_id' => 0
                        );
                        $connection->getCommandBuilder()->createInsertCommand('mp_sale_log', $data)->execute();
                    }
                    $transaction->commit();
                    //$this->SendOrderToClaris($data);
                } catch (Exception $e) {
                    $transaction->rollback();
                    $error = $e->getMessage();
                    echo $error->message;
                }
                unset($_COOKIE['basket']);
                setcookie('basket', null, -1, '/');
                Yii::app()->user->setFlash('sucess', 'Ваш заказ успешно принят. Номер Вашего заказа: . С Вами будет работать персональный менеджер, который будет вести контроль над всеми этапами Вашего заказа, от оформления до выдачи товара. Персональный менеджер информирует Вас о готовности заказа, после чего Вы сможете получить товар как с помощью доставки, так и путем самовывоза.');
                $this->refresh();
            }
        }

        $this->render('order', array('products' => $products, 'orderPrefix' => $orderPrefix, 'model' => $model, 'region' => $region));
    }

    public function SendOrderToClaris($data) {
        $claris_url = 'http://nightly.claris.su/6878/mspares.ashx';
        $ch = curl_init($claris_url);
        $order = array(
            'user_email' => $data['Users']['user_email'],
            'user_phone' => $data['Users']['user_phone'],
            'user_name' => $data['Users']['user_name'],
            'user_address' => $data['Users']['user_address'],
            'shipping_type' => $data['delivery'] == 0 ? 'Samovivoz' : 'Dostavka',
            'order_dtime' => date('Y-m-d H:i:s', time()),
        );
        if ($order['shipping_type'] == 'Dostavka') {
            $order['shipping'] = array(
                'delivery_title' => $shipping['delivery_title'],
                'delivery_sum' => $shipping['delivery_sum'],
            );
        }
        $order['products'][] = array(
            'product_id' => $product['product_unicode'],
            'storage_id' => $storage['warehouse_claris'],
            'product_quantity' => $product['product_count'],
        );
        $claris['orders'] = json_encode($order); //SITE_ALL | OBRATNIY_ZVONOK | ORDER_PRICE
        curl_setopt_array(
                $ch, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $claris)
        );
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            echo $error['message'];
        }
        $this->render('error');
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($model->subject) . '?=';
                $headers = "From: $name <{$model->email}>\r\n" .
                        "Reply-To: {$model->email}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-Type: text/plain; charset=UTF-8";

                mail(Yii::app()->params['adminEmail'], $subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}
